const _ = require("@/libs/underscore/underscore-min.js")._

// json 转 表单
export const json2Form = json =>{
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}


export const isJSON = (str) => {
		if (typeof str == 'string') {
		try {
			var obj=JSON.parse(str);
			if(typeof obj == 'object' && obj ){
				return true;
			}else{
				return false;
			}
		} catch(e) {
			console.log('error：'+str+'!!!'+e);
			return false;
		}
	}
}

// showRequestErrorToast
export const showRequestErrorToast = () =>{
  uni.showToast({
    icon: 'none',
    title: '系统繁忙，请稍后再试'
  });
}

// 获取软件id
export const getWxAppId = str =>{
  return 1
}

// export const avatarUrl = 'http://lorempixel.com/30/30/'
// export const avatarUrl = "http://placeimg.com/30/30"
export const avatarUrl = 'https://picsum.photos/30'

export const getRandMobile = () => {
	let prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "150", "155", "156", "158", "159", "170", "185", "186", "187", "189");
	let i = parseInt(10 * Math.random())
	let prefix = prefixArray[i]
	prefix = prefix + '****'
	prefix = prefix + parseInt(10 * Math.random()).toString()
	prefix = prefix + parseInt(10 * Math.random()).toString()
	prefix = prefix + parseInt(10 * Math.random()).toString()
	prefix = prefix + parseInt(10 * Math.random()).toString()
	return prefix
}
// 保存token
export const saveToken = params =>{
  uni.setStorage({
    key: 'storage_app_token',
    data: params.data,
    success: params.success,
    fail: params.fail,
    complete: params.complete,
  });
}

// 获取token
export const getToken = () =>{
  return uni.getStorageSync('storage_app_token')
}

// 保存openid
export const saveOpenid = params =>{
  uni.setStorage({
    key: 'storage_app_openid',
    data: params.data,
    success: params.success,
    fail: params.fail,
    complete: params.complete,
  });
}

// 获取openid
export const getOpenid = () =>{
  return uni.getStorageSync('storage_app_openid')
}

// 保存preference
export const savePreference = params =>{
  uni.setStorage({
    key: 'storage_app_preference',
    data: params.data,
    success: params.success,
    fail: params.fail,
    complete: params.complete,
  });
}

// 获取preference
export const getPreference = () =>{
  return uni.getStorageSync('storage_app_preference')
}

// 保存token
export const saveCurrentCity = params =>{
  uni.setStorage({
    key: 'storage_app_current_city',
    data: params.data,
    success: params.success,
    fail: params.fail,
    complete: params.complete,
  });
}

// 获取token
export const getCurrentCity = () =>{
  return uni.getStorageSync('storage_app_current_city')
}

// 保存软件信息
export const saveAppInfo = json =>{
  uni.setStorage({
    key: 'storage_app_info',
    data: json
  });
}

// 获取软件信息
export const getAppInfo = () =>{
  let info = uni.getStorageSync('storage_app_info');
  info.navigationBarHeight = info.platform == "android" ? 50 : 46;
  return info
}

// 保存历史城市选择
export const saveHistoryCityInfo = json =>{
  uni.setStorage({
    key: 'storage_app_history_city_info',
    data: json
  });
}

// 获取软件信息
export const getHistoryCityInfo = () =>{
  return uni.getStorageSync('storage_app_history_city_info')
}

export const formatDateTime = (timeStamp,format,isfull,cn) => {
	var date = new Date();
	isfull?date.setTime(timeStamp):date.setTime(timeStamp * 1000);
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? ('0' + m) : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	var h = date.getHours();
	h = h < 10 ? ('0' + h) : h;
	var minute = date.getMinutes();
	var second = date.getSeconds();
	minute = minute < 10 ? ('0' + minute) : minute;
	second = second < 10 ? ('0' + second) : second;
	if(format=='yyyy-MM-dd hh:mm:ss')return cn?(y+'年'+m+'月'+d+'日 '+h+':'+minute+':'+second):(y+'-'+m+'-'+d+' '+h+':'+minute+':'+second);
	if(format=='yyyy-MM-dd mm:ss')return cn?(y+'年'+m+'月'+d+'日 '+minute+':'+second):(y+'-'+m+'-'+d+' '+minute+':'+second);
	if(format=='yyyy-MM-dd')return cn?(y+'年'+m+'月'+d+'日'):(y+'-'+m+'-'+d);
	if(format=='yyyy-MM')return cn?(y+'年'+m+'月'):(y+'-'+m);
	return (y+'年'+m+'月'+d+'日');
}

// 验证手机号码
export const validateMobile = (mobile) => {
  var myreg = /^1[3|4|5|6|7|8|9]\d{9}$/;
  if(mobile.length==0)return false;
  if(mobile.length!=11)return false;
  if(!myreg.test(mobile))return false;
  return true;
}

// 验证邮箱
export const validateEmail = (email) => {
  var myreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if(!myreg.test(email))return false;
  return true;
}

// rpx2px
export const rpx2px = (px) =>{
  let ratio = getAppInfo().ratio
  return px / ratio
}

export const encodeGoodId = (id) =>{
	let code = '';
	let map = {
		0: ['A','!','T','n','U'],
		1: ['B','@','S','m','V'],
		2: ['C','#','R','l','W'],
		3: ['D','$','Q','k','X'],
		4: ['E','%','P','j','Y'],
		5: ['F','^','O','i','Z'],
		6: ['G','&','L','h','a'],
		7: ['H','*','N','g','b'],
		8: ['I','(','M','f','c'],
		9: ['J',')','K','e','d'],
	}
	id = id.toString().split('');

	_.each(id, (v) => {
		code += map[v] ? map[v][Math.floor(Math.random()*(4+1))] : v
	})

	return code
}

export const decodeGoodId = (code) =>{
	let id = '';
	let map = {
		0: ['A','!','T','n','U'],
		1: ['B','@','S','m','V'],
		2: ['C','#','R','l','W'],
		3: ['D','$','Q','k','X'],
		4: ['E','%','P','j','Y'],
		5: ['F','^','O','i','Z'],
		6: ['G','&','L','h','a'],
		7: ['H','*','N','g','b'],
		8: ['I','(','M','f','c'],
		9: ['J',')','K','e','d'],
	}
	code = code.toString().split('');
	_.each(code, (v) => {
		let bool = false;
		let res = '';

		_.each(map, (value, key) => {
			if(!bool){
				if(_.indexOf(value, v) > -1){
					res = key;
					bool = true;
				}
			}
		})

		id += bool ? res : v;
	})
	return id
}

// drawRoundRect
export const drawRoundRect = (ctx, x, y, w, h, r) => {
  var min_size = Math.min(w, h);
  if (r > min_size / 2) r = min_size / 2;
  // 开始绘制
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.arcTo(x + w, y, x + w, y + h, r);
  ctx.arcTo(x + w, y + h, x, y + h, r);
  ctx.arcTo(x, y + h, x, y, r);
  ctx.arcTo(x, y, x + w, y, r);
  ctx.closePath();
}

// drawText
export const drawText = (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) => {
  let lineWidth = 0;    
  let lastSubStrIndex = 0; //每次开始截取的字符串的索引  
  for (let i = 0; i < str.length; i++) {        
    lineWidth += ctx.measureText(str[i]).width;        
    if (lineWidth > canvasWidth) {            
      ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分            
      initHeight += 18; //22为 文字大小20 + 2            
      lineWidth = 0;            
      lastSubStrIndex = i;            
      titleHeight += 18;
    }        
    if (i == str.length - 1) { //绘制剩余部分            
      ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);        
    }    
  }    // 标题border-bottom 线距顶部距离    
  titleHeight = titleHeight + 10;    
  return titleHeight;
}

export const urlParams = (search) => {
	var array = {};
	if(search != undefined){
		search = search.split('#')[0];
		search = search.split('&');
		_.each(search,function(v){
			var o = v.split('=');
			array[o[0]]=o[1];
		});
	}
	return array
}